#include "stdafx.h"

#include "BankData.h"

#include "TransactionManager.h"


PC2::TransactionManager::TransactionManager( ApplicationSettings* apSettings )
	: m_Coordinator(apSettings->m_NodeInfo, apSettings->m_Parts, apSettings->m_DBPath.c_str())
{
	printf("TransactionManager %s\n", apSettings->m_NodeInfo.m_Name.c_str());
	for (auto it = apSettings->m_Parts.begin(); it != apSettings->m_Parts.end(); it++)
	{
		m_BankSet.insert(it->m_Name);
	}

	m_Coordinator.SetExecutor(this);
}

void PC2::TransactionManager::Exec()
{
	printf("recovery if needed\n");
	std::string lData;
	int status = m_Coordinator.Recovery(&lData);
	if(1 == status)
	{
		BankTransaction* lpTrans = (BankTransaction*)lData.c_str();
		printf("last trans succeed\n");
	}
	else if(-1 == status)
	{
		printf("last trans failed\n");
	}
	printf("recovery finished\n");

	printf("waiting for new command from client\n");
	while (true)
	{
		m_Coordinator.WaitAndRunOnce(1000*10);
	}
}

bool PC2::TransactionManager::PrepareClientRequest(char const* apReceivedData, uint32_t aReceivedSize)
{
	BankTransaction* lpTrans = (BankTransaction*)apReceivedData;
	printf("received transaction name %s from %s to %s value %u\n"
		, lpTrans->m_Name, lpTrans->m_BankFrom, lpTrans->m_BankTo, lpTrans->m_Value);
	if(m_BankSet.end() != m_BankSet.find(lpTrans->m_BankFrom)
		&& m_BankSet.end() != m_BankSet.find(lpTrans->m_BankTo))
	{
		return true;
	}
	else
	{
		printf("bank name not found\n");
		return false;
	}
}
